package com.poker.util;

import com.poker.bean.ResultBean;
import com.google.gson.Gson;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public final class Misc {

    private static final Logger logger = LoggerFactory.getLogger(Misc.class);

    private static final String DF_YMD = "yyyy-MM-dd";

    private static final char[] CODES = "0123456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ".toCharArray();

    public static boolean isEmpty(Object object) {
        return null == object || String.valueOf(object).trim().length() == 0;
    }

    public static boolean isNotEmpty(Object object) {
        return !isEmpty(object);
    }

    public static String toJson(boolean success, String message, Object data) {
        ResultBean bean = new ResultBean();
        bean.setSuccess(success);
        bean.setMessage(message);
        bean.setData(data);
        return new Gson().toJson(bean);
    }

    public static String randomCode(int len) {
        return random(len);
    }

    private static String random(int len) {
        Random random = new Random();
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < len; ++i) {
            buf.append(Misc.CODES[random.nextInt(Misc.CODES.length)]);
        }
        return buf.toString();
    }

    /**
     * @param: [password, salt:盐值, hashIterations:散列次数];
     * @return: java.lang.String;
     * @Description: Shiro MD5盐值加密;
     */
    public static String getShiroMd5Pwd (String password, String salt, int hashIterations) {
        password = new SimpleHash("md5", password, ByteSource.Util.bytes(salt), hashIterations).toHex();
        return password;
    }

    /**
     * @param: [request, response, storePath:数据库存储文件路径];
     * @return: void;
     * @Description: 文件下载;
     */
    @SneakyThrows(IOException.class)
    public static void download(HttpServletResponse response, String storePath) {
        File file = new File(storePath);

        if(!file.exists()) {
            logger.info("路径：" + storePath + "对应的文件不存在！");
            toWeb(response, "sorry~, no file found!");
            return;
        }

        String fileName = System.currentTimeMillis() + storePath.substring(storePath.lastIndexOf("."));
        fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        response.setContentType("text/x-plain");
        response.setCharacterEncoding("UTF-8");

        @Cleanup OutputStream out = response.getOutputStream();
        @Cleanup InputStream is =  new FileInputStream(file);

        byte[] cache = new byte[4 * 1024];
        for (int offset = is.read(cache); offset != -1; offset = is.read(cache)) {
            out.write(cache, 0, offset);
        }

        out.flush();

    }

    /**
     * @param: [response, object];
     * @return: void;
     * @Description: 数据返回流;
     */
    @SneakyThrows(IOException.class)
    private static void toWeb(HttpServletResponse response, Object object) {
        response.setContentType("text/html;charset=UTF-8");
        @Cleanup PrintWriter objPw = response.getWriter();

        objPw.print(object);
        objPw.flush();
    }

    /**
     * 格式化日期为YYYY-MM-DD形式的字符串。
     * 如果参数为空，则返回当前时间
     *
     * @param date 日期
     * @return 格式化的日期字符串
     */
    public static String getDefDate(Date date) {
        if (null == date) { date = new Date(System.currentTimeMillis()); }
        DateFormat df = new SimpleDateFormat(DF_YMD);
        return df.format(date);
    }

}
